package com.hqyj.springbootdemo01.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.springbootdemo01.common.component.JwtComponent;
import com.hqyj.springbootdemo01.common.result.PageResult;
import com.hqyj.springbootdemo01.common.result.Result;
import com.hqyj.springbootdemo01.common.utils.RedisUtils;
import com.hqyj.springbootdemo01.user.dto.UserInfo;
import com.hqyj.springbootdemo01.user.dto.UserPageInfo;
import com.hqyj.springbootdemo01.user.dto.UserRole;
import com.hqyj.springbootdemo01.user.entity.User;
import com.hqyj.springbootdemo01.user.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author sdx2009
 * @package com.hqyj.springbootdemo01.user.controller
 * @date 2022/8/25 15:10
 */

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtComponent jwtComponent;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisUtils redisUtils;


    @GetMapping("/list")
    public JSONObject getUserList() {
        List<UserInfo> userList = new ArrayList<>();

        for (int i = 0; i < 7; i++) {
            UserInfo user = new UserInfo();
            user.setUserName("zhangsan" + i);
            user.setPassword("123456");

            userList.add(user);
        }

        JSONObject result = new JSONObject();
        result.put("code", 200);
        result.put("userList", userList);
        return result;
    }

    @GetMapping("/info")
    public JSONObject getUserInfo(UserInfo userInfo) {
        User user = userService.getUserInfo(userInfo);
        JSONObject result = new JSONObject();
        result.put("user", user);
        return result;
    }

    @PostMapping("/add")
    public JSONObject addUser(@RequestBody UserInfo userInfo) {
//        boolean addResult = userService.addUser(userInfo);
        boolean addResult = userService.addUserBatch(userInfo);
        JSONObject result = new JSONObject();
        if (addResult) {
            result.put("code", 200);
        } else {
            result.put("code", 500);
        }
        return result;
    }

    @GetMapping("/update")
    public Result<String> updateUser(UserInfo userInfo) {
//        boolean updateResult = userService.updateUser(userInfo);
//        boolean updateResult = userService.updateUserByWrapper(userInfo);
        boolean updateResult = userService.updateUserBatch(userInfo);
        if (updateResult) {
            return new Result<String>().success();
        } else {
            return new Result<String>().error();
        }
    }

    @GetMapping("/page")
    @RequiresAuthentication
    @RequiresRoles("admin")
    public PageResult<User> getUserPage(UserPageInfo userPageInfo) {
        Page<User> page = userService.getUserPage(userPageInfo);

        PageResult<User> result = new PageResult<>(200, "操作成功", page.getTotal(), page.getRecords(),
                page.getPages(), page.getCurrent());

//        把redis中的token删除
        redisTemplate.delete("token");

        return result;
    }

    @GetMapping("/role")
    public Result<?> getUserRole(Integer id) {
        UserRole userRole = userService.getUserRoleByUserId(id);
        if (null == userRole) {
            return new Result<>().error("查询结果为空");
        } else {
            return new Result<>().success().put(userRole);
        }
    }

    @GetMapping("/delete")
    public Result<?> deleteUser(Integer id) {
        boolean result = userService.deleteUser(id);
        if (result) {
            return new Result<>().success();
        } else {
            return new Result<>().error();
        }
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody UserInfo userInfo) {
        try {
//            UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(),
//                    userInfo.getPassword());
//            Subject subject = SecurityUtils.getSubject();
//            subject.login(token);

            User user = userService.getUserInfo(userInfo);
            if (Objects.isNull(user)) {
                //TODO 异常处理
                throw new UnauthorizedException();
//                return new Result<>().error();
            }

//        生成JWT token
            String jwtToken = jwtComponent
                    .sign(userInfo.getUserName(), userInfo.getPassword(), "web");

//            把token暂存在redis中
//            redisTemplate.opsForValue().set("token", jwtToken);
//            redisTemplate.expire("token", 30, TimeUnit.SECONDS);

//            等效于上边的两行代码
//            redisTemplate.opsForValue().set("token", jwtToken, 30, TimeUnit.SECONDS);

            redisUtils.setEx("token",jwtToken,30);

            return new Result<>().success().put(jwtToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new Result<>().error();
        }
    }

    @GetMapping("/401")
    public Result<?> unauthorization() {
        return new Result<>().error(401, "没有权限");
    }
}
